package com.fit.dao.user;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.ioc.annotations.Inject;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.fit.entities.User;

public class UserDAOImpl implements UserDAO {

	@Inject
	private Session session;

	public boolean save(User user) {
		if (user != null) {
			session.save(user);
			return true;
		}
		return false;
	}

	public User findById(Long id) {
		return (User) session.get(User.class, id);
	}

	public List<User> findAll() {
		return session.createCriteria(User.class).list();
	}

	public User findByUserNameAndPassword(String username, String password) {
		if (password == null || username == null) {
			return null;
		}

		if (password.equals("") || username.equals("")) {
			return null;
		}

		List l = session.createCriteria(User.class)
				.add(Restrictions.eq("username", username))
				.add(Restrictions.eq("password", password)).list();
		User u = null;
		if (l != null) {
			if (l.size() > 0) {
				u = (User) l.get(0);
			}
		}
		return u;
	}
	
	public User findByUsername(String username) {
		ArrayList<User> list = (ArrayList<User>) session
				.createCriteria(User.class)
				.add(Restrictions.eq("username", username)).list();
		if (list.size() == 0) {
			return null;
		}
		return list.get(0);
	}


	public boolean deleteByUsername(String username) {
		User temp = findByUsername(username);
		if(temp != null) {
			session.delete(temp);
			return true;
		}
		return false;
	}

	public boolean update(User user) {
		if(user !=null) {
			session.update(user);
			return true;
		}
		return false;
	}

}
